package com.yao.club.service.impl;

import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.SignLog;
import com.yao.club.entity.dto.UserPoint;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.SignLogRepository;
import com.yao.club.reposittory.UserPointRepository;
import com.yao.club.service.SignService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class SignServiceImpl implements SignService {

    @Autowired
    private SignLogRepository signLogRepository;

    @Autowired
    private UserPointRepository userPointRepository;


    @Autowired
    private UserMapper userMapper;




    @Override
    public ResponseEntity<Boolean> signIn(String username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }


        // 检查用户是否已经签到
        LocalDate today = LocalDate.now();
        SignLog existingLog = signLogRepository.findByUserIdAndSignDate(user.member_id, today);
        if (existingLog != null) {
            return ResponseUtils.failed("今天已经签到过了");
        }

        // 添加签到记录
        SignLog signLog = new SignLog();
        signLog.setUserId(user.member_id);
        signLog.setSignDate(today);
        signLog.setPointsEarned(5);
        signLogRepository.save(signLog);

        // 更新用户积分
        UserPoint userPoint = userPointRepository.findByUserId(user.member_id);
        if (userPoint == null) {
            userPoint = new UserPoint();
            userPoint.setUserId(user.member_id);
            userPoint.setPoints(5);
            userPoint.setLastSignDate(today);
            userPoint.setContinuousDays(1);
        } else {
            userPoint.setPoints(userPoint.getPoints() + 5);
            userPoint.setLastSignDate(today);
            userPoint.setContinuousDays(userPoint.getLastSignDate().equals(today.minusDays(1))
                    ? userPoint.getContinuousDays() + 1 : 1);
        }
        userPointRepository.save(userPoint);

        return ResponseUtils.success(true);
    }

    @Override
    public ResponseEntity<Boolean> isSignedInToday(String username) {
        UserEntity user = userMapper.select(username);
        if (user == null) {
            return ResponseUtils.failed("用户不存在");
        }

        // 检查今天是否有签到记录
        LocalDate today = LocalDate.now();
        SignLog existingLog = signLogRepository.findByUserIdAndSignDate(user.member_id, today);
        if (existingLog != null) {
            return ResponseUtils.success(true); // 已签到
        } else {
            return ResponseUtils.success(false); // 未签到
        }
    }
}